import Map from 'ol/Map.js'
import TileLayer from 'ol/layer/Tile.js'
import View from 'ol/View.js'
import WMTS from 'ol/source/WMTS.js'
import WMTSTileGrid from 'ol/tilegrid/WMTS.js'
import { fromLonLat, get as getProjection } from 'ol/proj.js'
import { getWidth } from 'ol/extent.js'

const map = new Map({
  target: 'map',
  view: new View({
    zoom: 15,
    center: fromLonLat([114.499147, 30.554964])
  })
})

let resolutions = []
const matrixIds = []
const proj3857 = getProjection('EPSG:3857')
const maxResolution = getWidth(proj3857.getExtent()) / 256

for (let i = 0; i < 24; i++) {
  matrixIds[i] = i.toString()
  resolutions[i] = maxResolution / Math.pow(2, i)
}

const tileGrid = new WMTSTileGrid({
  origin: [-20037508.342787, 20037508.342787],
  resolutions: resolutions,
  matrixIds: matrixIds
})

// For more information about the IGN API key see
// https://geoservices.ign.fr/blog/2021/01/29/Maj_Cles_Geoservices.html

const ign_source = new WMTS({
  url: 'https://218.106.119.50:6443/geoscene/rest/services/huashan/test/MapServer/WMTS',
  layer: 'huashan_test',
  matrixSet: 'default028mm',
  format: 'image/png',
  projection: 'EPSG:3857',
  tileGrid: tileGrid,
  style: 'default'
})

const ign = new TileLayer({
  source: ign_source
})

map.addLayer(ign)

window.map = map
